<template>
  <div>
    <div class="card px-3 pt-3 mb-3">
      <el-form @submit.native.prevent :inline="true">
        <el-form-item>
          <el-date-picker
            v-model="formData.dateYearMonth"
            type="month"
            placeholder="选择时间"
            format="yyyy年1月-M月"
            :picker-options="datePickerOptions"
            @change="handleQuery"
          ></el-date-picker>
        </el-form-item>
        <el-form-item>
          <select-address
            v-model="queryParams.addressCode"
            placeholder="地址查询"
            auto-top
            clearable
            :bottom-level="2"
            @change="handleQuery"
          ></select-address>
        </el-form-item>
        <el-form-item>
          <select-org-bank
            v-model="formData.bankId"
            placeholder="选择银行"
            filterable
            clearable
            @select="selectBank"
          ></select-org-bank>
        </el-form-item>
        <el-form-item>
          <c-select
            style="width: 140px"
            :options="enumBusType"
            number-key
            clearable
            placeholder="业务模式"
            v-model="formData.busType"
            @change="handleQuery"
          ></c-select>
        </el-form-item>
        <el-form-item>
          <select-main-business
            clearable
            placeholder="十二大产业分类"
            v-model="formData.mainBus"
            @change="handleSelectMainBus"
          ></select-main-business>
        </el-form-item>
        <el-form-item>
          <el-button :loading="loading" icon="el-icon-search" @click="listGetData()">
            查询
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <div class="row" v-loading="loading">
      <div class="col-md-8 col-sm-12">
        <div class="card p-3 mb-3" style="min-height: 200px">
          <div class="analy-title mb-3">项目统计分析</div>

          <div class="row">
            <div class="col-3" v-for="(o, i) in numOption" :key="i">
              <div class="text-muted">{{ o.label }}(万元)</div>
              <el-tooltip effect="light" placement="bottom-start" :disabled="!o.showTooltip">
                <div
                  class="stat-num mb-2"
                  :class="o.showTooltip ? 'cursor-pointer text-primary' : ''"
                >
                  <span class="mr-1">&yen;</span>
                  <span>{{ o.fundsFt }}</span>
                  <i class="fa fa-caret-down" v-if="o.showTooltip"></i>
                </div>
                <ul slot="content" class="list-unstyled">
                  <li>
                    <span class="stat-t-label">担保金额</span>
                    ： {{ o.funds }} 万元
                  </li>
                  <li>
                    <span class="stat-t-label">部分解保金额</span>
                    ： {{ o.partOutFunds }} 万元
                  </li>
                  <li>
                    <span class="stat-t-label">在保余额</span>
                    ： {{ o.leftFunds }} 万元
                  </li>
                </ul>
              </el-tooltip>
              <div
                class="stat-bar mb-2"
                :style="`--v-percent: ${o.percent}%;--stat-color:${o.color}`"
              ></div>
              <div class="stat-label">
                <span class="stat-count">{{ o.count }}</span>
                <span class="text-muted ml-1">个项目</span>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="col-md-4 col-sm-12">
        <div class="card mb-3">
          <el-echarts
            theme="macarons"
            :loading="loading"
            :height="198"
            :option="chartOption"
          ></el-echarts>
        </div>
      </div>
    </div>

    <div class="card p-3">
      <div class="d-flex justify-content-between mb-3">
        <div class="analy-title">项目详情数据</div>

        <div class="d-flex">
          <el-radio-group class="anylay-type-radio mr-3" v-model="projectType">
            <el-radio-button
              v-for="(type, index) in enumProjectType"
              :key="index"
              :label="type.value"
            >
              <span class="mx-3">{{ type.label }}</span>
              <!-- <span>{{type.count}}</span> -->
            </el-radio-button>
          </el-radio-group>
          <el-button
            :loading="downloadLoading"
            type="text"
            icon="el-icon-download"
            @click="exportExcel()"
          >
            下载{{ projectTypeLabel }}项目
          </el-button>
        </div>
      </div>

      <div v-show="projectType === 0">
        <analy-list
          ref="listRef0"
          :query-params="inQueryParams"
          @getData="handleInData"
        ></analy-list>
      </div>
      <div v-show="projectType === 1">
        <analy-list
          ref="listRef1"
          :query-params="outQueryParams"
          @getData="handleOutData"
        ></analy-list>
      </div>
      <div v-show="projectType === 2">
        <analy-list
          ref="listRef2"
          :query-params="newQueryParams"
          :order-params="{ load_date: 'desc' }"
          @getData="handleNewData"
        ></analy-list>
      </div>
    </div>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { getMonthLastDayDate } from '@/common/plugins/tools/date'
import { stringFormatDot, dateFormat, sub, addressCut } from '@vimi/utils-tool'
import { getParams, enumBusType, enumProjectType } from './reportMixins'
import { num } from '@/common/plugins/tools/format'

import SelectAddress from '@/components/select/SelectAddress'
import SelectOrgBank from '@/bigcredit/views/program/components/SelectOrgBank'
import SelectMainBusiness from '@/credit/components/select/SelectMainBusiness'
import AnalyList from '@/credit/views/city/report/AnalyList'

export default {
  components: {
    SelectAddress,
    SelectOrgBank,
    AnalyList,
    SelectMainBusiness,
  },
  props: {},
  data() {
    return {
      enumBusType,
      loading: false,
      downloadLoading: false,
      formData: {
        dateYearMonth: new Date(),
        bankId: '',
        busType: '',
        mainBus: '',
      },
      queryParams: {
        clientId: '',
        addressCode: '',
        startDate: '',
        endDate: '',
        bankCode: '',
        busStatus: '',
        guaType: '1,2,3,4',
        mainBus: '',
      },
      datePickerOptions: {
        disabledDate: time => time.getTime() > Date.now(),
      },

      chartOption: {},
      numOption: [],

      enumProjectType,
      projectType: 0,
    }
  },
  computed: {
    ...mapGetters(['clientId']),
    projectTypeLabel() {
      const item = enumProjectType.find(it => it.value === this.projectType)
      return item ? item.label : ''
    },
    inQueryParams() {
      return {
        ...this.queryParams,
        busStatus: 0,
      }
    },
    outQueryParams() {
      return {
        ...this.queryParams,
        busStatus: 1,
      }
    },
    newQueryParams() {
      return {
        ...this.queryParams,
        busStatus: 2,
      }
    },
  },
  watch: {},
  created() {
    this.setDateParams()
    this.getData()
  },
  mounted() {},
  methods: {
    setDateParams() {
      const date = new Date()
      const year = date.getFullYear()
      const month = date.getMonth()
      const start = new Date(year, 0, 1)
      const end = getMonthLastDayDate(year, month)

      this.formData.dateYearMonth = date
      this.queryParams.startDate = start
      this.queryParams.endDate = end
      this.queryParams.clientId = this.clientId
    },
    async getData() {
      const lastYear = this.queryParams.endDate.getFullYear() - 1
      const lastYearEnd = getMonthLastDayDate(lastYear, 11)

      this.loading = true
      const [res] = await this.$utils.promise(
        Promise.all([
          this.getInData(),
          this.getOutData(),
          this.getNewCreateData(),
          this.getLastYearInData(),
          // 本年部分解保金额
          this.getPartOutFunds(this.queryParams),
          // 上年部分解保金额
          this.getPartOutFunds({
            ...this.queryParams,
            startDate: new Date(lastYear, 0, 1),
            endDate: lastYearEnd,
          }),
        ])
      )
      this.loading = false

      const defaultData = { count: 0, funds: 0 }
      const [
        inData = defaultData,
        outData = defaultData,
        newCreateData = defaultData,
        lastYearInData = defaultData,
        partOutFunds = 0,
        lastPartOutFunds = 0,
      ] = res || []
      const data = {
        currIn: {
          label: '本年在保',
          color: '#1dd1a1',
          ...inData,
          showTooltip: true,
          partOutFunds,
          leftFunds: Math.max(0, sub(inData.funds, partOutFunds)),
        },
        currOut: {
          label: '本年解保',
          color: '#fd8a25',
          ...outData,
        },
        currNew: {
          label: '本年新增',
          color: '#4ff0ff',
          ...newCreateData,
        },
        lastIn: {
          label: '上年在保',
          color: '#5cb0ff',
          ...lastYearInData,
          showTooltip: true,
          partOutFunds: lastPartOutFunds,
          leftFunds: Math.max(0, sub(lastYearInData.funds, lastPartOutFunds)),
        },
      }
      this.setNumOption(data)
      this.setOption(data)
    },
    listGetData() {
      this.getData()
      const { listRef0, listRef1, listRef2 } = this.$refs
      listRef0 && listRef0.getData()
      listRef1 && listRef1.getData()
      listRef2 && listRef2.getData()
    },

    // 在保统计数
    getInData() {
      const params = getParams({ ...this.queryParams, busStatus: 0 })
      return this.getCountData(params)
    },

    // 解保统计数
    getOutData() {
      const params = getParams({ ...this.queryParams, busStatus: 1 })
      return this.getCountData(params)
    },

    // 新增统计数
    getNewCreateData() {
      const params = getParams({ ...this.queryParams, busStatus: 2 })
      return this.getCountData(params)
    },

    // 上年在保
    getLastYearInData() {
      const lastYear = this.queryParams.endDate.getFullYear() - 1
      const end = getMonthLastDayDate(lastYear, 11)

      const params = getParams({
        ...this.queryParams,
        startDate: new Date(lastYear, 0, 1),
        endDate: end,
        busStatus: 0,
      })
      return this.getCountData(params)
    },

    // 获取部分解保金额
    async getPartOutFunds(queryParams) {
      const { startDate, endDate, clientId, bankCode, mainBus, guaType, addressCode } = queryParams
      const params = {
        apiKey: 'ungua-funds-part',
        start_time: dateFormat(startDate, 'yyyy-MM-dd'),
        end_time: dateFormat(endDate, 'yyyy-MM-dd'),
        service_id: clientId,
        address_code: addressCode ? addressCut(addressCode) + '%' : undefined,
        bank_code: bankCode || undefined,
        main_business: mainBus || undefined,
        gua_type: guaType === void 0 || guaType === '1,2,3,4' ? undefined : guaType || '1,2,4',
      }

      const res = await this.$http.get('/api/credit/view/getUnguaFundsPart', { params })
      return num(res.data?.unGuaFunds?.unGuaFunds)
    },

    handleInData(data) {
      this.enumProjectType[0].count = data.totalCount
    },
    handleOutData(data) {
      this.enumProjectType[1].count = data.totalCount
    },
    handleNewData(data) {
      this.enumProjectType[2].count = data.totalCount
    },

    getCountData(params) {
      return this.$api
        .getData(this.$serviceName, 'market_project', {
          groupFunc: 'count(customer_related_id),round(sum(warranty_amount)|2)',
          isBIQuery: 1,
          ...params,
        })
        .then(res => {
          const data = (res && res.data && res.data[0]) || {}
          return {
            count: +data.p || 0,
            funds: +data.p1 || 0,
          }
        })
    },

    exportExcel() {
      const listRef = this.$refs[`listRef${this.projectType}`]
      if (listRef) {
        this.downloadLoading = true
        listRef.exportExcel(`${this.projectTypeLabel}项目`).finally(() => {
          this.downloadLoading = false
        })
      }
    },

    handleYearPick() {
      this.formData
    },
    handleQuery() {
      const { dateYearMonth, busType, isProGua } = this.formData

      // 时间处理
      if (!dateYearMonth) {
        this.setDateParams()
      } else {
        this.queryParams.startDate = new Date(dateYearMonth.getFullYear(), 0, 1)
        this.queryParams.endDate = getMonthLastDayDate(
          dateYearMonth.getFullYear(),
          dateYearMonth.getMonth()
        )
      }

      // 业务类型
      this.queryParams.guaType = busType === 1 ? '4' : busType === 0 ? '1,2,3' : '1,2,3,4'
      this.queryParams.isProGua = isProGua
      this.getData()
    },
    selectBank(bank) {
      this.queryParams.bankCode = bank.agency_code || ''
      this.getData()
    },
    handleSelectMainBus() {
      this.queryParams.mainBus = this.formData.mainBus
      this.getData()
    },

    setNumOption({ lastIn, currIn, currOut, currNew }) {
      // 总数：上年在保+本年新增
      const total = lastIn.count + currNew.count
      const toP = n => (total ? Math.round((n * 100) / total) : 0)
      this.numOption = [lastIn, currNew, currOut, currIn].map(it => ({
        ...it,
        fundsFt: stringFormatDot(it.funds),
        percent: toP(it.count),
      }))
    },
    // 图表
    setOption({ lastIn, currIn, currOut, currNew }) {
      const createBar = (data, index) => ({
        name: data.label,
        type: 'bar',
        stack: 'Total',
        barMaxWidth: 40,
        label: {
          show: true,
          position: 'top',
        },
        itemStyle: {
          color: data.color,
        },
        data: [
          ...Array(index).fill('-'),
          {
            value: data.count,
            ...data,
          },
          ...Array(Math.max(3 - index, 0)).fill('-'),
        ],
      })

      this.chartOption = {
        title: {
          text: '项目统计瀑布图',
          textStyle: {
            fontSize: 14,
          },
          top: 10,
          left: 10,
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow',
          },
          formatter: params => {
            const { name, dataIndex } = params[0]
            const { count, funds } = params[dataIndex + 1].data
            return `${name}<br/>项目：${count} 个<br/>金额：${funds}万元`
          },
        },
        legend: {
          show: false,
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true,
        },
        xAxis: {
          type: 'category',
          data: ['上年在保', '本年新增', '本年解保', '本年在保'],
        },
        yAxis: {
          type: 'value',
          splitLine: {
            show: false,
          },
        },
        series: [
          {
            name: 'placeholder',
            type: 'bar',
            stack: 'Total',
            itemStyle: {
              borderColor: 'transparent',
              color: 'transparent',
            },
            emphasis: {
              itemStyle: {
                borderColor: 'transparent',
                color: 'transparent',
              },
            },
            data: [0, lastIn.count, lastIn.count + currNew.count - currOut.count, 0],
          },
          ...[lastIn, currNew, currOut, currIn].map(createBar),
        ],
      }
    },
  },
}
</script>

<style lang="scss" scoped>
@import './analy.scss';

.stat-num {
  font-family: Arial, Helvetica, sans-serif;
  font-weight: bold;
  font-size: 1.5rem;
  display: flex;
  align-items: center;

  i.fa {
    font-size: 1rem;
    color: $primary;
    margin-left: 0.5rem;
  }
}
.stat-t-label {
  display: inline-block;
  min-width: 85px;
  text-align: justify;
  text-align-last: justify;
}
.stat-bar {
  position: relative;
  height: 4px;
  width: 80%;

  &::before {
    content: '';
    position: absolute;
    left: 0;
    top: 0;
    height: 100%;
    width: 100%;
    background-color: $gray-200;
  }

  &::after {
    content: '';
    position: absolute;
    left: 0;
    top: 0;
    height: 100%;
    width: var(--v-percent);
    background-color: var(--stat-color);
  }
}
.stat-label {
  position: relative;
  display: inline-block;
  color: $gray-600;
  margin-right: 0.5rem;
}
.stat-count {
  color: #333;
  font-weight: bold;
  font-size: 1.1rem;
}
</style>
